package dao.Implementation;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import Donnees.Note;
import Util.HibernateUtil;
import dao.Interfaces.INoteDAO;

public class NoteDAO implements INoteDAO {
	public NoteDAO() {
	}
	
	public List<Note> selectAll() {
		List<Note> listeNote = new ArrayList<Note>();

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		listeNote.addAll(session.createQuery("from Note").list());

		session.flush();
		tx.commit();
		session.close();

		return listeNote;
	}

	public long insert(Note f) {
		Note noteTemp = f;
		Long msgId;

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		msgId = (Long) session.save(noteTemp);

		session.flush();
		tx.commit();
		session.close();
		
		return msgId;
	}
	
	public int delete(Note f) {
		Note noteTemp = f;
		int retour;
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		
		retour = session.createQuery("delete from Note where id='" + noteTemp.getId() + "'").executeUpdate();

		session.flush();
		tx.commit();
		session.close();
		
		return retour;
	}
	
	public Note getById(long id) {
		Note noteTemp = new Note();

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		noteTemp = (Note) session.createQuery("from Note where id='" + id + "'").list().get(0);

		session.flush();
		tx.commit();
		session.close();

		return noteTemp;
	}
}
